//
//  ST_ParentStyleRegisterController.swift
//  btvideo
//
//  Created by mac on 2020/9/27.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SwiftyJSON

class ST_ParentStyleRegisterController: UIViewController ,ST_RegisterRouteProtocol{
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        view.addSubview(progress_view)
        progress_view.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 25)
            make.height.equalTo(2)
        }
        
        view.addSubview(title_nav_btn)
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(progress_view.snp.bottom).offset(26)
            make.height.equalTo(24)
        }
        
        view.addSubview(sub_title_label)
        sub_title_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(title_nav_btn.snp.bottom).offset(4)
            make.height.equalTo(20)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(sub_title_label.snp.bottom)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview()
        }
        
        binding()
        
        
        pull_observer.onNext(())
        
        back_thread_execute(afterDelay: 1) {
            ST_RegisterMonitor.shared.logger.report(fromController: self)
        }
    }
    
    
    fileprivate func binding(){
        
        Observable.combineLatest(pull_observer, SCComponets.config_component.boot_config_observer).subscribe(onNext: {[weak self] _ , state in
            
            if state == .finished{
                self?.request_data()
            }
            
        }).disposed(by: disposeBag)
        
    }
    
    //    MARK: - Properties
    
    
    
    var disposeBag = DisposeBag()
    
    fileprivate let pull_observer = PublishSubject<Void>()
    
    fileprivate lazy var progress_view: registerProgressView = {
        let v = registerProgressView()
        v.setProgress(currentIndex: 2, amount: 4)
        return v
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
        
        var genderStr = "女生"
        if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex, sex == .female {
            genderStr = "男生"
        }
        control.setTitleForAllStates("选择你喜欢的" + genderStr + "特质")
        
        return control
    }()
    
    fileprivate lazy var sub_title_label: UILabel = {
        let l = UILabel()
        l.text = "特质用户都通过了AI精准人脸认证"
        l.textColor = UIColor.init(hex: 0x999999)
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.contentInset = UIEdgeInsets.init(top: 20, left: 0, bottom: 25+BTSafeAreaBottom, right: 0)
        
        control.register(cellWithClass: ParentStyleRegisterCell.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = .white
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        return control
    }()
    
    fileprivate lazy var cellHeight = (ScreenWidth - 30)/345.0*156 + 10
    
    fileprivate lazy var data_array = [ST_PeculiarityModel]()
}

//MARK: - Request
extension ST_ParentStyleRegisterController{
    
    func request_data(){
        
        
        var param = ["gender":"2"]
        
        if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex,sex == .female{
            param.updateValue("1", forKey: "gender")
        }
        
        JVrequest(PH.peculiarityListForRegisterApi,parameters: param, success: { (json) in
            
            if let list = [ST_PeculiarityModel].deserialize(from: json["data"].rawString() ?? "") as? [ST_PeculiarityModel]{
                
                self.data_array = list
            }
            
            self.tableView.reloadData()
            
        }) { (code, err) in
            
            //            ToastHud(text: err, view: self.view)
            
            main_thread_execute(afterDelay: 1.5) {
                
                self.pull_observer.onNext(())
                
            }
        }
    }
    
}


//MARK: - UITableViewDelegate
extension ST_ParentStyleRegisterController:UITableViewDelegate,UITableViewDataSource{
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ParentStyleRegisterCell.self, for: indexPath)
        
        cell.model = data_array[indexPath.row]
        
        cell.isTop = indexPath.row == 0
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let item_model = data_array[safe:indexPath.row]  else{return}
        
        
        //        let json = JSON(["id":item_model.id.string,"title":item_model.name])
        
        //        let value = json.rawString() ?? ""
        
        //        RegisterStepPersistence.update(raw: value, step: TianRegisterStep.styleParent)
        
        //TianRegisterStepManager.shared.pushNextStepAction()
        
        self.pushNextRegisterController(parameters: ["id":item_model.id.string,"title":item_model.name])
    }
}



//MARK: - Cell
class ParentStyleRegisterCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        self.contentView.backgroundColor = UIColor.white
        
        cover_image_view.cornerRadius = 15
        contentView.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: 10, right: 0))
        }
        
        contentView.addSubview(coverTitleLabel)
        coverTitleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalTo(cover_image_view).offset(-30)
            make.height.equalTo(24)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.bottom.equalTo(cover_image_view).offset(-10)
            make.height.equalTo(18)
        }
        
        
        contentView.addSubview(top_label)
        top_label.snp.makeConstraints { (make) in
            make.right.equalTo(cover_image_view).offset(-10)
            make.top.equalTo(cover_image_view).offset(10)
            make.width.equalTo(69)
            make.height.equalTo(25)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var coverTitleLabel:UILabel = {
        let control = UILabel()
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var top_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.text = "人气No.1!"
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.semibold)
        control.backgroundColor = UIColor.init(hex: 0xED3E58)
        control.cornerRadius = 12
        control.alpha = 0
        return control
    }()
    
    
    var isTop = false{
        didSet{
            top_label.alpha = isTop ? 1 : 0
        }
    }
    
    var model = ST_PeculiarityModel(){
        didSet{
            
            
            cover_image_view.pin_setImage(from: model.register_image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            coverTitleLabel.text = model.name
            
            var genderStr = "个女生"
            if let sex = ST_RegisterMonitor.shared.regist_response_account()?.userinfo?.sex,sex == .female{
                genderStr = "个男生"
            }
            
            content_label.text = model.own_num.string + genderStr
            
            
            
        }
    }
    
}
